#!/usr/bin/python
#coding=utf-8

import tornado.httpserver
import tornado.ioloop
import tornado.options
import tornado.web

import urllib2
import cookielib


from tornado.options import define, options

define ("port",default=8000,help="run on the port",type=int)

class indexHandler(tornado.web.RequestHandler):
		def get(self):
				greeting=self.get_argument('greeting','hellomeng')
				self.write( greeting+" meng\n")

class miHandler(tornado.web.RequestHandler):
		def get(self):
				cj = cookielib.CookieJar()
				post_data = urllib.urlencode({'passToken':'', 'user': 'mengqingxi89@126.com', 'pwd': 'm123456789', 'callback':'https://account.xiaomi.com', 'sid':'passport', 'qs':'%3Fsid%3Dpassport', 'hidden':'', '_sign':'KKkRvCpZoDC+gLdeyOsdMhwV0Xg='})
				path = 'http://order.xiaomi.com/login/callback?followup=http%3A%2F%2Fwww.xiaomi.com%2Findex.php&sign=ZjEwMWVlOTY3MWM1OGE3YjYxNGRiZjQ5MzJmYjI5NDE0ZWY0NzY5Mw%2C%2C&pwd=1&usr=mengqingxi89%40126.com&auth=gUDk76OWEwNOHGwwQnOyXKSIZH8ej6CKl4Iaju6IbladzGSVfQyw5OM5Fk3wRE7tpbQbhR6NtIJ5H5gReX1bFvckSOGKznFnsmCNs%2F6f3TTsy7vRKbkbUDTc5SLcTfycYg9mLbI4UZzQtkkMD1%2Bi3pv%2B8wKLSUUlJfrjeo65hX8%3D&nonce=kaSf6QbPTzIBYlZC&_ssign=2F89%2BbpX%2FTWBRkQqEA4CBkqn9C4%3D'
				cookieHandle = urllib2.HTTPCookieProcessor(cj)
				opener = urllib2.build_opener(cookieHandle)
				#opener.addheaders = [('User-agent', 'Opera/9.23')]
				urllib2.install_opener(opener)
				req = urllib2.Request(path, post_data)
				response = urllib2.urlopen(req)
				html = response.read()
				self.render("mibuy.html",message=html)


if __name__=="__main__":
	tornado.options.parse_command_line()
	app=tornado.web.Application(handlers=[(r"/",indexHandler)
					,(r"/mi/",miHandler)])
	http_server=tornado.httpserver.HTTPServer(app)
	http_server.listen(options.port)
	tornado.ioloop.IOLoop.instance().start()